<script setup lang="ts">
import {computed, onBeforeMount, onMounted, ref} from "vue";
import {
  deleteDocumentById,
  deleteDocumentsByIds,
  downloadDocument,
  getUserDocuments,
  updateDocument
} from "../../apis/DocumentApi.js";
import { useRoute } from "vue-router";
import { elPrompt } from "../../utils/elPrompt.ts";
import { Document } from "../../interfaces/Document.ts";
import { Result } from "../../interfaces/Result.ts";
import router from "../../router/router.js";
import {useUserStore} from "../../stores/userStore.ts";
import showSize from "../../utils/showSize.js";
import {User} from "../../interfaces/User.ts";

const user = useUserStore()

let userId = 0
onBeforeMount(() => {
  userId = parseInt(<string>useRoute().params.userId)
  documentsUserId.value = userId
  init()
})


const userDocuments = ref<Document[]>()
const pageNumber = ref(1)
const pageSize = ref(10)
const total = ref(10)
const pageSizes = computed(() => {
  const numberArray = [10]
  let maxPageSize = numberArray[0]
  while (maxPageSize < total.value) {
    maxPageSize += 10
    numberArray.push(maxPageSize)
  }
  return numberArray
})

onMounted(() => {
  loadData()
})

function loadData() {
  getUserDocuments(userId,
    (result) => {
      if (result.status !== 200) return elPrompt(result.message, "error")
      userDocuments.value = result.data['dataLists']
      total.value = result.data['total']
    },
    pageNumber.value,
    pageSize.value,
    searchTitle.value,
    searchKeyword.value
  )
}

function previewDocument(documentId: number) {
  window.open(`/document/preview/${documentId}`, '_target')
}

const dialog = ref({
  visible: false,
  title: '',
  content: '',
  onCancel: () => { },
  onContinue: () => { },
  showDialog: (title?: string, content?: string, onCancel?: Function, onContinue?: Function) => {
    dialog.value.visible = true
    if (title) dialog.value.title = title
    if (content) dialog.value.content = content
    if (onCancel) dialog.value.onCancel = onCancel
    if (onContinue) dialog.value.onContinue = onContinue
  },
  closeDialog: () => {
    dialog.value.visible = false
  },
  cancel: () => {
    dialog.value.closeDialog()
    if (dialog.value.onCancel) dialog.value.onCancel()
  },
  delete: () => {
    dialog.value.closeDialog()
    if (dialog.value.onContinue) dialog.value.onContinue()
  }
})

let document: Document
function beforeDeleteDocument(doc: Document) {
  document = doc
  dialog.value.showDialog('删除文档', `确认删除${doc.title}?`, null, deleteDocument)
}
function deleteDocument() {
  deleteDocumentById(document.id, (result: Result<any>) => {
    if (result.status !== 200) return elPrompt(result.message, 'error')
    elPrompt('删除成功', 'success')
    dialog.value.visible = false
    loadData()
  })
}

const documentIds = ref<number[]>()
function beforeDeleteDocuments(ids: number[] | undefined) {
  documentIds.value = ids
  dialog.value.showDialog('批量删除文档', `确认删除${documentIds.value?.length}个文档?`, null, deleteDocuments)
}
function deleteDocuments() {
  deleteDocumentsByIds(documentIds.value, (result: Result<any>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    elPrompt('批量删除成功！', "success")
    loadData()
  })
}

function editDocument(documentId: number) {
  router.push(`/document/edit/${documentId}`)
}

function selectDocument(documents: Document[]) {
  documentIds.value = []
  if (!(documents.length > 0)) return
  documents.forEach((item) => {
    documentIds.value?.push(item.id)
  })
}

function handleSizeChange(value: number) {
  pageNumber.value = 1
  pageSize.value = value
  loadData()
}

function handleCurrentChange(value: number) {
  pageNumber.value = value
  loadData()
}

function getIconClass(title: string) {
  const documentType = title.slice(title.lastIndexOf('.') + 1)
  const icon = {
    doc: 'iconfont icon-word',
    docx: 'iconfont icon-word',
    xls: 'iconfont icon-excel',
    xlsx: 'iconfont icon-excel',
    ppt: 'iconfont icon-ppt',
    pptx: 'iconfont icon-ppt',
    pdf: 'iconfont icon-pdf',
  }
  return icon[documentType]
}

const canDeleteDocuments = computed(() => {
  return !(documentIds.value?.length > 0)
})
const searchTitle = ref('')
const searchKeyword = ref('')
function resetSearch() {
  searchTitle.value = ''
  searchKeyword.value = ''
  loadData()
}

const loginUserId = ref(0)
const documentsUserId = ref(-1)
function init() {
  user.getValue().then((loginUser:User) => {
    loginUserId.value = loginUser.id
  })
}
const isSelfDocument = computed( () => {
  return documentsUserId.value === loginUserId.value
})

async function changeIsPublic(document: Document) {
  if (!isSelfDocument) return
  document.isPublic = (document.isPublic === '公开') ? '私有' : '公开'
  await save(document)
  loadData()
}

async function save(document: Document) {
   await updateDocument(document, (result:Result<any>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    elPrompt('修改成功！', "success")
  })
}
</script>

<template>
  <div class="operation">
    <el-input placeholder="标题" v-model="searchTitle" @keydown.enter="loadData"/>
    <el-input placeholder="关键词" v-model="searchKeyword" @keydown.enter="loadData"/>
    <el-button @click="loadData">搜索</el-button>
    <el-button @click="resetSearch" type="warning">重置搜索</el-button>
    <el-button @click="beforeDeleteDocuments(documentIds)" type="danger" :disabled="canDeleteDocuments" v-if="isSelfDocument">批量删除</el-button>
  </div>
  <div class="table-data">
    <el-table :data="userDocuments" @selection-change="selectDocument" height="75vh">
      <el-table-column type="selection" width="50" v-if="isSelfDocument"/>
      <el-table-column prop="title" label="标题">
        <template #default="scope">
          <i :class="getIconClass(scope.row.title)" />
          <span class="windows-open" @click="previewDocument(scope.row.id)">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="size" width="200" label="大小">
        <template #default="scope">
          {{ showSize(scope.row.size) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" width="200" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" width="200" label="上传时间" />
      <el-table-column prop="updateTime" width="200" label="更新时间" />
      <el-table-column prop="commentStatus" width="200" label="评论区状态">
        <template #default="scope">
          <el-tag :type="scope.row.commentStatus === '开启' ? 'success' : 'danger'">{{ scope.row.commentStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isPublic" width="200" label="是否公开">
        <template #default="scope">
          <el-tag @click="changeIsPublic(scope.row)" :type="scope.row.isPublic === '公开' ? 'success' : 'danger'">
            <span class="windows-open">{{ scope.row.isPublic }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300">
        <template #default="scope">
          <el-button @click="previewDocument(scope.row.id)">预览</el-button>
          <el-button @click="downloadDocument(scope.row.id)" type="warning">下载</el-button>
          <el-button v-if="isSelfDocument" @click="editDocument(scope.row.id)" type="primary">编辑</el-button>
          <el-button v-if="isSelfDocument" @click="beforeDeleteDocument(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="pageNumber" v-model:page-size="pageSize" :page-sizes="pageSizes"
      :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <div class="dialog">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="30%">
      <span>{{ dialog.content }}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.cancel()">取消</el-button>
          <el-button type="danger" @click="dialog.delete()">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.operation {
  display: flex;

  .el-input {
    margin-right: 10px;
    width: 200px;
  }

  .el-button {
    margin-right: 10px;
  }
}

.table-data {
  .iconfont {
    margin-right: 5px;
  }
  .windows-open:hover {
    text-decoration: underline;
    font-weight: bold;
    color: var(--color-danger);
  }
}

.page {
  z-index: 100;
  position: absolute;
  bottom: 50px;
  background: white;
}
</style>